package android.framework.binding;

public abstract class BaseBindable<T> implements IBindable<T>{
	private MultiBindingAdapter<T> listener = new MultiBindingAdapter<T>();
	private long lastActionId = -1;
	
	public void addListener(IObserver<T> listener) {
		this.getListener().addObserver(listener);
	}
	
	public void removeListener(IObserver<T> listener){
		this.getListener().removeObserver(listener);
	}
	
	protected void notifyListener(T value){
		lastActionId = Binding.getNextActionId();
		notifyListener(value, lastActionId);
	}
	
	private void notifyListener(T value, long actionId){
		if(getListener() != null){
			getListener().notifyChanges(value, actionId);
		}
	}
	
	protected abstract void notifyChanges(T value);
	
	public boolean notifyChanges(T value, long actionId){
		if(actionId > lastActionId){
			this.lastActionId = actionId;
			notifyChanges(value);
			notifyListener(value, actionId);
			return true;
		}
		return false;
	}

	public MultiBindingAdapter<T> getListener() {
		return listener;
	}

	public void setListener(MultiBindingAdapter<T> listener) {
		this.listener = listener;
	}
	
	public void clearListeners(){
		listener.clear();
	}
}
